#ifndef __DATA_FIFO_H_
#define __DATA_FIFO_H_

#include "bsp_spi.h"

#define MAX_DATA_FIFO 3

typedef struct
{
  uint16_t length;
  uint8_t data[SPI_TRANS_DATA_BUFF_SIZE];
}data_msg_t;

typedef struct
{ 
  data_msg_t data_msg[MAX_DATA_FIFO];
  
  uint8_t write;
  uint8_t read;
  uint8_t count;
  
}data_fifo_t;


static inline void data_fifo_empty(data_fifo_t *fifo)
{
  fifo->write = 0;
  fifo->read = 0;
  fifo->count = 0;
}

static inline int data_fifo_write(data_fifo_t *fifo, uint8_t *data, uint16_t length)
{
    if (fifo->count < MAX_DATA_FIFO)
    {
        if (length == 0)
        {
          return 0;
        }

				fifo->data_msg[fifo->write].length = length;
				memcpy(fifo->data_msg[fifo->write].data, data, length);

				fifo->count ++;
				fifo->write ++;
				if (fifo->write >= MAX_DATA_FIFO)
				{
						fifo->write = 0;
				}

				return 1;
    }

    return 0;
}


static inline int data_fifo_read(data_fifo_t *fifo, uint8_t *data, uint16_t *length)
{
    if (fifo->count > 0)
    {
        memcpy(data, fifo->data_msg[fifo->read].data, fifo->data_msg[fifo->read].length);
        *length = fifo->data_msg[fifo->read].length;
        
        fifo->data_msg[fifo->read].length = 0;

        fifo->count --;
        fifo->read ++;
        if (fifo->read >= MAX_DATA_FIFO)
        {
            fifo->read = 0;
        }

        return 1;
    }

    return 0;
}

static inline int data_fifo_first_size_read(data_fifo_t *fifo)
{
    return fifo->data_msg[fifo->read].length;
}


#endif
